<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Partner;
use App\Http\Controllers\LayuiController as Layui;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use SuperClosure\Serializer;
use App\Jobs\ExportData;
use Illuminate\Support\Facades\DB;

class PartnerController extends Controller
{
    /**
     * 列表展示页
     *
     * @Author   qizhifei
     * @DateTime 2019-06-01
     * @return   [type]     [description]
     */
    public function index()
    {
        return view('Admin.partner.index');
    }

    /**
     * 获取数据方法
     *
     * @Author   qizhifei
     * @DateTime 2019-06-01
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function table(Request $request)
    {
        $payload = $request->all();
        $data = Partner::with(["provinceInfo", "cityInfo"])
            ->where(function ($query) use ($payload) {
                if (isset($payload['phone']) && $payload['phone'] != '') {
                    $query->Where('phone', 'like', "%$payload[phone]%");
                }
                if (isset($payload['name']) && $payload['name'] != '') {
                    $query->Where('name', 'like', "%$payload[name]%");
                }
                if (isset($payload['datetime']) && $payload['datetime'] != '') {
                    $datetime = explode(' ~ ', $payload['datetime']);
                    try {
                        $starttime = Carbon::parse($datetime[0] ?? '')->toDateTimeString();
                        $endtime = Carbon::parse($datetime[1] ?? '')->toDateTimeString();
                    } catch (\Exception $exception) {
                        throw new FormException('请选择有效查询范围');
                    }
                    $query->whereBetween('created_at', [$starttime, $endtime]);
                }
                if (isset($payload['region']) && $payload['region'] != '') {
                    $query->Where('region', 'like', "%$payload[region]%");
                }
            })
            ->orderBy('created_at', 'desc')
            ->get();
        return Layui::tableJson($data, 0, $data->count());
    }


    /**
     * 数据导出
     *
     * @Author   qizhifei
     * @DateTime 2019-06-01
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function export(Request $request)
    {
        $payload = $request->all();
        $filename = $request->input('filename', 'demo.csv');
        $filename = rtrim($filename, '.csv') . '.csv';

        if (Storage::disk('exports')->exists($filename))
            return $this->getResponse('文件已存在，请重新输入', [], 302, url('admin/partner/index'));
        //判断前台是否有选择
        if (empty($payload['ids'])) {
            /* 获取查询条件 */
            $query = function () use ($payload) {
                return DB::table('partner')
                    ->when(!is_null($phone = array_get($payload, 'phone')), function ($query) use ($phone) {
                        $query->where('partner.phone', 'like', "%$phone%");
                    })
                    ->when(!is_null($name = array_get($payload, 'name')), function ($query) use ($name) {
                        $query->where('partner.name', 'like', "%$name%");
                    })
                    ->when(!is_null($region = array_get($payload, 'region')), function ($query) use ($region) {
                        $query->where('partner.region', 'like', "%$region%");
                    })
                    ->when(!is_null($datetime = array_get($payload, 'datetime')), function ($query) use ($datetime) {
                        $datetime = explode(' ~ ', $payload['datetime']);
                        try {
                            $starttime = Carbon::parse($datetime[0] ?? '')->toDateTimeString();
                            $endtime = Carbon::parse($datetime[1] ?? '')->toDateTimeString();
                        } catch (\Exception $exception) {
                            throw new FormException('请选择有效查询范围');
                        }
                        $query->whereBetween('created_at', [$starttime, $endtime]);
                    })
                    ->orderBy('created_at', 'desc')
                    ->select('partner.id as id', 'partner.name as name', 'partner.phone as phone','partner.region as region', 'partner.created_at as created_at');
            };
        } else {
            //有选择
            $ids = explode(',', $payload['ids']);
            $query = function () use ($ids) {
                return DB::table('partner')
                    ->whereIn('id', $ids)
                    ->orderBy('created_at', 'desc')
                    ->select('partner.id as id', 'partner.name as name', 'partner.phone as phone', 'partner.region as region', 'partner.created_at as created_at');
            };
        };

        /* 定义文件头 */
        $header = [
            'id' => '序号',
            'name' => '姓名',
            'phone' => '手机号码',
            'created_at' => '申请时间',
            'region' => '所在城市',
        ];

        /* 插入队列 */
        /* 闭包序列化处理 */
        $serializer = new Serializer();
        dispatch(new ExportData($header, $serializer->serialize($query), '', $filename));
        return $this->getResponse('已加入导出队列', [], 200, url('admin/partner'));
    }


}
